const str = Math.random().toString(36).substr(2);
const time = new Date().getTime();
module.exports = class extends think.Model {

    async register(data) {
        if (!think.isEmpty(await this.checkUser({email: data.email}))) {
            throw false
        }
        const token = await this.model('token/token').addToken();
        Object.assign(data, {
            user_id: await think.$tools.getMd5(str + time + Math.random()),
            token_id: token.token_id,
        });
        this.add(data);
        return Object.assign(data, {token: token.token});
    }

    async login(data) {
        data.password = await think.$tools.sha512(data.password, 'c3f6$^$$^&6b015 a1849');
        const userInfo = await this.where(data).select();
        if (think.isEmpty(userInfo)) {
            throw false
        } else {
            const token = await this.model('token/token').updateToken(userInfo);
            token.user_id = JSON.parse(JSON.stringify(userInfo))[0].user_id;
            return token
        }
    }

    async setPassword(data) {
        data.password = await think.$tools.sha512(data.password, 'c3f6$^$$^&6b015 a1849');
        return this.where({email: data.email}).update({password: data.password});
    }

    async checkUser(data) {
        return this.where(data).find();
    }

    async checkUserToken(data) {
        return this.alias('table_a').join({
            user: {
                on: {
                    user_id: 'user_id',
                }
            },
            token: {
                as: 'table_b',
                on: {
                    token_id: 'token_id'
                }
            },
        }).where({'table_b.token': data.token, 'table_a.user_id': data.user_id}).find();
    }

};
